package com.czk.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/3 20:30
 */
public class ZookeeperConnection {
    public static void main(String[] args) throws IOException {
        // 由于zookeeper连接是异步的，所以需要经主线程阻塞
        CountDownLatch countDownLatch=new CountDownLatch(1);
        ZooKeeper zooKeeper=new ZooKeeper("192.168.25.133:2181", 10000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                // 连接成功
                if (watchedEvent.getState()==Event.KeeperState.SyncConnected){
                    System.out.println("连接创建成功");
                    // 释放主线程
                    countDownLatch.countDown();
                }
            }
        });
        // 阻塞主线程
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
